package com.easepal802s.project.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AlertDialog;

import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.easepal7506a.project.manager.DataManager;
import com.easepal7506a.project.observer.UpdataObserver;
import com.easepal802s.project.R;
import com.easepal802s.project.application.MyApplication;
import com.easepal802s.project.utils.ActivityUtils;
import com.easepal802s.project.widget.AutoLinkStyleTextView;
import com.example.reslib.utils.DisplayUtil;
import com.example.reslib.utils.PreferenceWrapper;
import com.example.reslib.utils.ToastUtils;
import com.ogawa.a7517.Constant;
import com.ogawa.a7517.activity.MainActivity7517;
import com.ogawa.base.Constant.UrlPathConstant;
import com.ogawa.base.download.AlertDialogUpdata;
import com.ogawa.base.download.AlertDialogUpdataProgress;
import com.ogawa.base.download.DownloadApkRequest;
import com.ogawa.base.download.DownloadInfoBean;
import com.ogawa.base.download.DownloadThreadPool;
import com.ogawa.base.network.bean.BeanUpdata;
import com.ogawa.base.utils.CommonUtil;
import com.ogawa.base.utils.ProjectSPUtils;
import com.ogawa.chair7808.bean.TempDevice7808StateBean;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import java.lang.ref.WeakReference;
import java.text.NumberFormat;

import static com.ogawa.base.Constant.Constant.DEVICE_7506;
import static com.ogawa.base.Constant.Constant.DEVICE_7506L;
import static com.ogawa.base.Constant.Constant.DEVICE_7507;
import static com.ogawa.base.Constant.Constant.DEVICE_7517;
import static com.ogawa.base.Constant.Constant.DEVICE_7808Core;
import static com.ogawa.base.Constant.Constant.DEVICE_802;


public class ChooseActivity extends Activity implements View.OnClickListener, UpdataObserver.OnUpdatasterner {
    private ImageView mIvNext;
    private TextView mTv7506;
    private TextView mTv802;
    private TextView mTv7506L;
    private TextView mTv7507;
    private TextView mTv7517;
    private TextView tv_7808;
    private int mChoose = DEVICE_802;//1 代表802  2:7506
    private IntentFilter intentFilter;
    private static boolean isNetCanuse = true;
    private TextView mTvTitle;
    private boolean hadDoUpdata;
    private String mSaveVersion = "";
    private int mSaveCount = 0;
    private boolean flag;

    private String mDownUrl;
    private NumberFormat numberFormat;
    private String TAG = "download_log";
    private AlertDialogUpdata mAler;
    private AlertDialogUpdataProgress mAlertProgress;
    private DownloadApkRequest request;
    private MyHandler mHandler;
    private boolean isDownFaile;
    private BeanUpdata mUpdataBean;
    private boolean isFirst;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        InitSystemBar(true);
        setContentView(R.layout.activity_choose);
        mSaveVersion = ProjectSPUtils.INSTANCE.getSaveVersion();
        mSaveCount = ProjectSPUtils.INSTANCE.getSaveCount();
        isFirst = ProjectSPUtils.INSTANCE.getIsFirst();
        mIvNext = findViewById(R.id.iv_next);
        mTv802 = findViewById(R.id.tv_802);
        mTv7506 = findViewById(R.id.tv_7506);
        mTv7506L = findViewById(R.id.tv_7506l);
        mTv7507 = findViewById(R.id.tv_7507);
        mTv7517 = findViewById(R.id.tv_7517);
        tv_7808 = findViewById(R.id.tv_7808);
        mTvTitle = findViewById(R.id.title);
        mChoose = ProjectSPUtils.INSTANCE.getAppSp();
        mHandler = new MyHandler(this);
        numberFormat = NumberFormat.getPercentInstance();
        numberFormat.setMinimumFractionDigits(2);
        if (mChoose == DEVICE_802) {
            mTv802.setSelected(true);
        } else if (mChoose == DEVICE_7506) {
            mTv7506.setSelected(true);
        } else if (mChoose == DEVICE_7506L) {
            mTv7506L.setSelected(true);
        } else if (mChoose == DEVICE_7507) {
            mTv7507.setSelected(true);
        } else if (mChoose == DEVICE_7517) {
            mTv7517.setSelected(true);
        }else if (mChoose == DEVICE_7808Core) {
            tv_7808.setSelected(true);
        }


        CommonUtil.setMargins(mTvTitle, 0, CommonUtil.getStatusBarHeight(this) + DisplayUtil.dip2px(this, 10), 0, 0);
        intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

        mTv7506.setOnClickListener(this);
        mTv802.setOnClickListener(this);
        mIvNext.setOnClickListener(this);
        mTv7506L.setOnClickListener(this);
        mTv7507.setOnClickListener(this);
        mTv7517.setOnClickListener(this);
        tv_7808.setOnClickListener(this);
        UpdataObserver.getInst().registerObserver(this);
        mUpdataBean = DataManager.getInst().getmUpdataBean();
        Log.e("mSave", mSaveCount + "===" + mSaveVersion);
        if (DataManager.getInst().getmUpdataBean() != null && !TextUtils.isEmpty(DataManager.getInst().getmUpdataBean().getUrl())) {
            if (mUpdataBean.getIsforce() == 1) {
                getPer();
            } else if (!mSaveVersion.equals(DataManager.getInst().getmUpdataBean().getAppversion()) || mSaveCount <= 3) {
                getPer();
            }

        }
        if (isFirst) {
            showYsxyDialog();
        }


//        TempDevice7808StateBean.FunctionsBean  functionsBean = new TempDevice7808StateBean.FunctionsBean();
//        TempDevice7808StateBean.FunctionsBean.AirCellFootSideBean bean = new TempDevice7808StateBean.FunctionsBean.AirCellFootSideBean();
//        bean.setFunctionCode("code");
//        bean.setFunctionName("name");
//        bean.setItemName("itemname");
//        bean.setModelValue("modevalue");
//        functionsBean.setAirCellFootSide(bean);
//        com.ogawa.chair7808.manager.DataManager.getInst().analysisDeviceStatusBean(functionsBean);
//        LogUtils.e("device:" + com.ogawa.chair7808.manager.DataManager.getInst().getDevice7808StateBean());
//
//
//        TempDevice7808StateBean.FunctionsBean  functionsBean2 = new TempDevice7808StateBean.FunctionsBean();
//        TempDevice7808StateBean.FunctionsBean.TimeRemainingBean wbean = new TempDevice7808StateBean.FunctionsBean.TimeRemainingBean();
//        wbean.setFunctionCode("code");
//        wbean.setFunctionName("name");
//        wbean.setItemName("itemname");
//        wbean.setModelValue("modevalue");
//        functionsBean2.setTimeRemaining(wbean);
//        com.ogawa.chair7808.manager.DataManager.getInst().analysisDeviceStatusBean(functionsBean2);
//        LogUtils.e("device:" + com.ogawa.chair7808.manager.DataManager.getInst().getDevice7808StateBean());
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void doUpdata(BeanUpdata bean) {
        if (!hadDoUpdata && !TextUtils.isEmpty(bean.getUrl())) {
            mUpdataBean = bean;
            if (bean.getIsforce() == 1) {
                getPer();
            } else if (!mSaveVersion.equals(DataManager.getInst().getmUpdataBean().getAppversion()) || mSaveCount <= 3) {
                getPer();
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        UpdataObserver.getInst().removeObserver(this);
    }

    public void InitSystemBar(boolean isStatus) {
        if (isStatus && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
        }
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
//        // 使用颜色资源
        tintManager.setStatusBarTintResource(R.color.clear);
    }

    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    @Override
    public void onClick(View v) {
        PreferenceWrapper preferenceWrapper = new PreferenceWrapper();
        switch (v.getId()) {
            case R.id.iv_next:
                ProjectSPUtils.INSTANCE.setAppSp(String.valueOf(mChoose));
                if (mChoose == DEVICE_802) {
                    ActivityUtils.startHomeActivity(ChooseActivity.this, "");
                    ChooseActivity.this.finish();
                } else if (mChoose == DEVICE_7517) {
                    Intent intent = new Intent(this, MainActivity7517.class);
                    if (preferenceWrapper.getBooleanValue(Constant.FIRST_IN, true)) {
                        intent.putExtra(Constant.FIRST_IN, true);
                    }
                    startActivity(intent);
                    finish();
                }else if (mChoose == DEVICE_7808Core) {
                    Object navigation = ARouter.getInstance().build(UrlPathConstant.ACTIVITY_7808_MAIN)
                            .navigation();
                    ChooseActivity.this.finish();
                } else {
                    ActivityUtils.startHome7506Activity(ChooseActivity.this, mChoose == DEVICE_7506L || mChoose == DEVICE_7507);
                    ChooseActivity.this.finish();
                }
                break;
            case R.id.tv_802:
                mChoose = DEVICE_802;
                mTv7506.setSelected(false);
                mTv802.setSelected(true);
                mTv7506L.setSelected(false);
                mTv7507.setSelected(false);
                mTv7517.setSelected(false);
                tv_7808.setSelected(false);
                break;
            case R.id.tv_7506:
                mTv7506.setSelected(true);
                mTv802.setSelected(false);
                mTv7506L.setSelected(false);
                mTv7507.setSelected(false);
                mTv7517.setSelected(false);
                tv_7808.setSelected(false);
                mChoose = DEVICE_7506;
                break;
            case R.id.tv_7506l:
                mTv7506.setSelected(false);
                mTv802.setSelected(false);
                mTv7506L.setSelected(true);
                mTv7507.setSelected(false);
                mTv7517.setSelected(false);
                tv_7808.setSelected(false);
                mChoose = DEVICE_7506L;
                break;
            case R.id.tv_7507:
                mTv7506.setSelected(false);
                mTv802.setSelected(false);
                mTv7506L.setSelected(false);
                mTv7507.setSelected(true);
                mTv7517.setSelected(false);
                tv_7808.setSelected(false);
                mChoose = DEVICE_7507;
                break;
            case R.id.tv_7517:
                mTv7506.setSelected(false);
                mTv802.setSelected(false);
                mTv7506L.setSelected(false);
                mTv7507.setSelected(false);
                mTv7517.setSelected(true);
                tv_7808.setSelected(false);
                mChoose = DEVICE_7517;
                break;
            case R.id.tv_7808:
                mTv7506.setSelected(false);
                mTv802.setSelected(false);
                mTv7506L.setSelected(false);
                mTv7507.setSelected(false);
                mTv7517.setSelected(false);
                tv_7808.setSelected(true);
                mChoose = DEVICE_7808Core;
                break;
        }
    }


    @Override
    public void toUpdata(BeanUpdata bean) {
        if (!ChooseActivity.this.isFinishing()) {
            doUpdata(bean);
        }

    }

    private void onPermissionSuccess() {
        showUpdataAlert(DataManager.getInst().getmUpdataBean());
    }


    public void getPer() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {//
            //开启定位权限,200是标识码
            Log.e("onActivityResult", "1");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200);
        } else {
            Log.e("onActivityResult", "2");
            onPermissionSuccess();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 200://刚才的识别码
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {//用户同意权限,执行我们的操作
                    onPermissionSuccess();//
                } else {//用户拒绝之后,当然我们也可以弹出一个窗口,直接跳转到系统设置页面
                    showPermissionDialog();
                }
                break;
            default:
                break;
        }

    }


    private AlertDialog mPermissionDialog;

    private void showPermissionDialog() {
        if (mPermissionDialog == null) {
            mPermissionDialog = new AlertDialog.Builder(this)
                    .setMessage("已禁用权限，请手动授予")
                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mPermissionDialog.cancel();
                            Uri packageURI = Uri.parse("package:" + getPackageName());
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                            startActivityForResult(intent, 2);

                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mPermissionDialog.cancel();
                        }
                    })
                    .create();
        }
        mPermissionDialog.show();
        mPermissionDialog.setCanceledOnTouchOutside(false);
        Button button = mPermissionDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        button.setTextColor(this.getResources().getColor(R.color.red));
        button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
        Button button2 = mPermissionDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
        button2.setTextColor(this.getResources().getColor(R.color.color_2121));
        button2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("onActivityResult", requestCode + "====" + resultCode);
        if (requestCode == 2) {
            //设置结果显示框的显示数值
            getPer();
        }
    }

    public void fileDownload(String url) {
        hadDoUpdata = true;
        request = new DownloadApkRequest(this, mHandler, url, new DownloadApkRequest.IDownloadApkInterProgress() {
            @Override
            public void onDownloadWait(DownloadInfoBean apkInfoBean) {
                isDownFaile = false;
            }

            @Override
            public void onDownloadStart(DownloadInfoBean apkInfoBean) {
                isDownFaile = false;
            }

            @Override
            public void onDownloadProgress(DownloadInfoBean apkInfoBean) {
                isDownFaile = false;
                String downloadLength = Formatter.formatFileSize(getApplicationContext(), apkInfoBean.getCurrentPos());
                String totalLength = Formatter.formatFileSize(getApplicationContext(), apkInfoBean.getEndPos());
                String size = downloadLength + "/" + totalLength;
                String speed = Formatter.formatFileSize(getApplicationContext(), apkInfoBean.getSpeed());
                String mSpeed = String.format("%s/s", speed);
                float pre = ((float) apkInfoBean.getCurrentPos()) / ((float) apkInfoBean.getEndPos());
                Log.e("cucucu", pre + "");
                String precent = numberFormat.format(pre);
                int mProgress = (int) (pre * 100);
                mAlertProgress.refreshView(size, precent, mSpeed, mProgress);
            }

            @Override
            public void onDownloadEnd(DownloadInfoBean dib) {
                Log.e("path", dib.getSavePath() + "");
                mAlertProgress.dismiss();

                CommonUtil.installApk(MyApplication.getContext(), dib.getSavePath());
            }

            @Override
            public void onDownloadFailed(DownloadInfoBean apkInfoBean, String errMsg) {
                isDownFaile = true;
                Log.e(TAG, errMsg + "");
                mAlertProgress.dismiss();
//                Log.e("isDownFaile",errMsg+"");
            }

        });
        DownloadThreadPool.getInstance().addTask(request);

    }


    private void showUpdataAlert(BeanUpdata bean) {
        mAler = new AlertDialogUpdata(this, bean, new AlertDialogUpdata.OnDialogListener() {

            @Override
            public void onClick() {
                if (bean.getIsforce() == 1) {
                    ToastUtils.showShortToast(ChooseActivity.this, "请升级后使用");
                    ChooseActivity.this.finish();
                } else {
                    mAler.dismiss();
                }
            }
        }, new AlertDialogUpdata.OnDialogListener() {
            @Override
            public void onClick() {
                Log.e("showUpdata", "showUpdataAlert");
                mDownUrl = bean.getUrl();
                mAlertProgress = new AlertDialogUpdataProgress(ChooseActivity.this, bean.getNotice());
                fileDownload(mDownUrl);
                mAlertProgress.setCancelable(false);
                mAlertProgress.show();
                mAler.dismiss();
                mAlertProgress.setOnDismissListener(new DialogInterface.OnDismissListener() {

                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        //处理监听事件
                        Log.e("showUpdata", "onDismiss");
                        DownloadThreadPool.getInstance().removeTask(request);

                    }
                });

            }
        });
        mAler.setCancelable(false);
        mAler.show();


    }


    protected static class MyHandler extends Handler {

        private WeakReference<ChooseActivity> wr;

        public MyHandler(ChooseActivity activity) {
            wr = new WeakReference<ChooseActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (wr != null && wr.get() != null) {
                wr.get().handleMessage(msg);
            }
        }

    }

    public void handleMessage(Message msg) {

    }

    public void showYsxyDialog() {

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        LayoutInflater inflater = this.getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_ysxy, null);
        dialogBuilder.setView(dialogView);
        TextView mTvExit = dialogView.findViewById(R.id.exit);
        TextView mTvOk = dialogView.findViewById(R.id.ok);
        AutoLinkStyleTextView autoLinkStyleTextView = dialogView.findViewById(R.id.tv);
        autoLinkStyleTextView.setOnClickCallBack(new AutoLinkStyleTextView.ClickCallBack() {
            @Override
            public void onClick(int position) {

                ActivityUtils.startWebViewActivity(ChooseActivity.this);
            }
        });


        final AlertDialog alertDialog = dialogBuilder.create();
        //加上下面两句才能显示圆角 不然圆角处会有白色效果
        Window window = alertDialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        alertDialog.setCancelable(false);
        alertDialog.show();
        mTvExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                System.exit(0);
            }
        });
        mTvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.cancel();
                ProjectSPUtils.INSTANCE.setIsFirst(false);
            }
        });
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = (int) (DisplayUtil.getScreenWidthPx(this) * 0.9); //设置宽度
        window.setAttributes(lp);


    }

    @Override
    public void onBackPressed() {
        if (flag) {
            ToastUtils.showShortToast(this, "取消升级?");
            flag = false;
            return;
        }
        super.onBackPressed();
    }
}

